# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from AlgorithmImports import *

### <summary>
### Regression algorithm for testing that period-based history requests are not allowed with tick resolution
### </summary>
class PeriodBasedHistoryRequestNotAllowedWithTickResolutionRegressionAlgorithm(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2013, 10, 8)
        self.SetEndDate(2013, 10, 9)

        spy = self.AddEquity("SPY", Resolution.Tick).Symbol

        # Tick resolution is not allowed for period-based history requests
        self.AssertThatHistoryThrowsForTickResolution(lambda: self.History[Tick](spy, 1),
            "Tick history call with implicit tick resolution")
        self.AssertThatHistoryThrowsForTickResolution(lambda: self.History[Tick](spy, 1, Resolution.Tick),
            "Tick history call with explicit tick resolution")
        self.AssertThatHistoryThrowsForTickResolution(lambda: self.History[Tick]([spy], 1),
            "Tick history call with symbol array with implicit tick resolution")
        self.AssertThatHistoryThrowsForTickResolution(lambda: self.History[Tick]([spy], 1, Resolution.Tick),
            "Tick history call with symbol array with explicit tick resolution")

        history = self.History[Tick](spy, TimeSpan.FromHours(12))
        if len(list(history)) == 0:
            raise Exception("On history call with implicit tick resolution: history returned no results")

        history = self.History[Tick](spy, TimeSpan.FromHours(12), Resolution.Tick)
        if len(list(history)) == 0:
            raise Exception("On history call with explicit tick resolution: history returned no results")

    def AssertThatHistoryThrowsForTickResolution(self, historyCall, historyCallDescription):
        try:
            historyCall()
            raise Exception(f"{historyCallDescription}: expected an exception to be thrown")
        except InvalidOperationException:
            # expected
            pass
